package ssm.dao.impl;

import ssm.dao.Search;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ChainOfResponsibilitySearch implements Search {
    /**
     * 责任链模式
     * @param conn
     * @param rs
     * @param rowsNumber
     * @throws SQLException
     */
    @Override
    public void check(Connection conn, ResultSet rs, int rowsNumber) throws SQLException {
        int count=0;
        for (int i = 1; i <= rowsNumber; i++) {
            rs.absolute(i);
            String rel_type = rs.getString("RelationType");
            if (rel_type.equalsIgnoreCase("aggregation")) {

                String s1 = rs.getString("SourceClass");
                String d1 = rs.getString("DestinationClass");

                if (s1.equalsIgnoreCase(d1)) {//2nd if composition with itself
                    for (int j = 1; j <= rowsNumber; j++) {
                        rs.absolute(j);
                        String rel_type2 = rs.getString("RelationType");
                        if (rel_type2.equalsIgnoreCase("REALIZATION")) {

                            String s2 = rs.getString("SourceClass");
                            String d2 = rs.getString("DestinationClass");
                            if (d2.equalsIgnoreCase(s1)) {

                                String sql2 = "INSERT INTO designs.chainofResponsibility_instances(Handler  ,ConcreteHandler) VALUES (?,?)";
                                PreparedStatement stmt2 = conn.prepareStatement(sql2);

                                stmt2.setString(1, s1);
                                stmt2.setString(2, s2);

                                int rows2 = stmt2.executeUpdate();
                                count+=rows2;
                            }
                        }
                    }
                }
            }
        }
        System.out.println("found " + count + " ChainOfResponsibility");
    }
}
